package com.ht.medicaltreatment.api

import android.util.Log
import com.blankj.utilcode.util.AppUtils
import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.gym.baselib.BaseApplication.Companion.context
import com.gym.baselib.utils.CacheUtils
import com.ht.medicaltreatment.base.CacheKey
import com.ihsanbal.logging.Level
import com.ihsanbal.logging.LoggingInterceptor
import com.xgst.lib.http.ApiResultCallAdapterFactory
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit


object RetrofitUtils {
    private var mRetrofit: Retrofit
    private lateinit var cookieJar:ClearableCookieJar
    init {
        cookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(context))

        val client = OkHttpClient().newBuilder().apply {
            readTimeout(60, TimeUnit.SECONDS)
            connectTimeout(60, TimeUnit.SECONDS)
            writeTimeout(60, TimeUnit.SECONDS)
            cookieJar(cookieJar)
            addInterceptor(ChangeBaseUrlInterceptor())
            //addInterceptor(LogInterceptor())
            addInterceptor(BusinessErrorInterceptor())
            addInterceptor(
                LoggingInterceptor.Builder()
                    .setLevel(Level.BASIC)
                    .log(Log.INFO)
                    .build()
            )
        }.build()

        mRetrofit = Retrofit.Builder()
            .client(client)
            .baseUrl("http://192.168.1.1:8080/")
            .addCallAdapterFactory(ApiResultCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun getCookie() = cookieJar

    private class ChangeBaseUrlInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            //获取Request
            val request = chain.request()
            //获取request的创建者builder
            val builder = request.newBuilder()
            val token = CacheUtils.getStringCache(CacheKey.TOKEN,"")
            builder.addHeader("Mobile-Custom-Token",token)
            val oldUrl = request.url

            val ip = CacheUtils.getStringCache(CacheKey.IP, "192.168.1.1")
            val port = CacheUtils.getStringCache(CacheKey.PORT, "8080")
            var url = "http://${ip}:$port/sample/other"
            if (AppUtils.isAppDebug()){
                url = "http://656c75a0.r23.cpolar.top/sample/other"
            }
            val newBaseUrl = url.toHttpUrl()
            val path = newBaseUrl.encodedPath+oldUrl.encodedPath
            val newFullUrl = oldUrl
                .newBuilder()
                .scheme(newBaseUrl.scheme)
                .host(newBaseUrl.host)
                .port(newBaseUrl.port)
                .encodedPath(path)
                .build()
            return chain.proceed(builder.url(newFullUrl).build())
        }
    }

    fun <T> initRetrofit(api: Class<T>): T {
        return mRetrofit.create(api)
    }

}